package com.whsxt.handler;

import com.whsxt.common.AjaxResult;
import com.whsxt.exception.BusinessException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.IOException;

/**
 * 自定义异常处理器类
 */
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public AjaxResult handleIllegalArgumentException(IllegalArgumentException e){
        System.out.println("发生了异常：" + e);
        return AjaxResult.error(e.getMessage());
    }

    @ExceptionHandler(BusinessException.class)
    @ResponseBody
    public AjaxResult handleBusinessException(BusinessException e){
        System.out.println("发生了异常:"+ e);
        System.out.println("当前异常的编号为：" + e.getCode());
        return AjaxResult.error(500,e.getMsg());
    }

    @ExceptionHandler(AuthorizationException.class)
    public void handleAuthorizationException(AuthorizationException e){
        System.out.println("发生了异常" + e);
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String contextPath = requestAttributes.getRequest().getServletContext().getContextPath();
        try {
            requestAttributes.getResponse().sendRedirect(contextPath + "/403.html");
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}
